package com.zb.zeus.common.redis.service.impl;

import com.zb.zeus.common.redis.service.IRoundExpireTime;

import cn.hutool.core.util.RandomUtil;

/**
 * 根据基准的百分比随机失效时间
 *
 * @author liangfan
 * @date 2021/07/13 10:28
 **/

public class PercentRoundExpireTime implements IRoundExpireTime {

    private static final long MIN = 0;
    private static final long MAX = 100;

    /**
     * 默认百分之十
     */
    private long percentValue = 10L;

    public PercentRoundExpireTime() {

    }

    public PercentRoundExpireTime(long percentValue) {
        if (percentValue < MIN || percentValue > MAX) {
            throw new IllegalArgumentException("percentValue must gt 0 and lt 100");
        }
        this.percentValue = percentValue;
    }

    @Override
    public long getExpireTimeByRound(long basicExpireTime) {
        if (basicExpireTime <= 0) {
            return basicExpireTime;
        }

        long l = (long) (basicExpireTime * percentValue * 0.01);
        long max = (l / 2);
        long min = max - l;
        long rand = RandomUtil.randomLong(min, max);
        return basicExpireTime + rand;
    }

    //    public static void main(String[] args){
    //        PercentRoundExpireTime percentRoundExpireTime = new PercentRoundExpireTime();
    //        System.out.println(percentRoundExpireTime.getExpireTimeByRound(10));
    //        System.out.println(percentRoundExpireTime.getExpireTimeByRound(100));
    //        System.out.println(percentRoundExpireTime.getExpireTimeByRound(200));
    //        System.out.println(percentRoundExpireTime.getExpireTimeByRound(500));
    //        System.out.println(percentRoundExpireTime.getExpireTimeByRound(1000));
    //    }
}
